package org.cfx.auth.interceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.cfx.auth.mapper.AuthRoleMapper;
import org.cfx.basic.annotation.Permission;
import org.cfx.basic.util.AjaxResult;
import org.cfx.basic.util.RedisUtil;
import org.cfx.org.domain.dto.EmployeeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthRoleMapper authRoleMapper;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 登录拦截,如果没有登录就要返回错误信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 获取请求头中的token
        String token = request.getHeader("TOKEN");
        response.setContentType("application/json;charset=UTF-8");

        // 2 如果token为空,说明未登录,要返回错误信息并拦截
        if(StringUtils.isBlank(token)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 3 根据token作为key,去redis中获取登录信息
        //与redis里的key比较是否存在
        EmployeeDto employee = redisUtil.getKey(token);
        if (employee == null){
            PrintWriter out = response.getWriter();
            //返回json {"success":true,"message":"请登录","data":"noAuth"}
            out.println("{\"success\":false,\"msg\":\"请登录\",\"data\":\"noLogin\"}");
            out.flush();
            out.close();
            //拦截
            return false;
        }

        // 鉴权 登录的用户是否有权限访问某些资源
        /*
           1.访问的方法是否要鉴权
                如果不需要，直接放行

           2.知道是什么角色，有哪些权限
                角色是否拥有该资源
         */
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //获取目标方法上的注解
        Permission annotation = method.getAnnotation(Permission.class);
        if (annotation!=null){//方法需要做鉴权
            //确定要做权限鉴定
            List<String> list = authRoleMapper.getSnByEmpId(employee.getUser().getId());

            String authRole = handlerMethod.getBeanType().getSimpleName()+":"+method.getName();
            if (!list.contains(authRole)) {
                PrintWriter out = response.getWriter();
                out.println("{\"success\":false,\"msg\":\"没有权限\",\"data\":\"Forbidden\"}");
                out.flush();
                out.close();
                return false;
            }
        }
        // 如果不为空,说明已经登录过就放行,并且重新给该key所在的redis设置30分钟过期时间
        redisTemplate.opsForValue().set(token, JSONUtil.toJsonStr(employee),30, TimeUnit.MINUTES);
        return true;
    }
}
